package com.william.springsecurity.handler;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.william.springsecurity.common.Result;
import com.william.springsecurity.config.RsaKeyProperties;
import com.william.springsecurity.pojo.SysUser;
import com.william.springsecurity.service.UserService;
import com.william.springsecurity.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

// 登录成功处理类
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler{

    @Autowired
    private RsaKeyProperties prop;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 生成jwt token 放入请求头
//        SysUser sysUser = (SysUser) authentication.getPrincipal();
        Object principal = authentication.getPrincipal();
        System.out.println(JSONUtil.toJsonPrettyStr(principal));
        String name = authentication.getName();
        System.out.println(name);
//        String token = jwtUtils.generateTokenExpireInMinutes(principal, prop.getPrivateKey(), 24 * 60);
        String token = jwtUtils.generateTokenExpireInMinutes(name, prop.getPrivateKey(), 24 * 60);
        // token存入redis
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setHeader(jwtUtils.getHeader(),token);
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = httpServletResponse.getWriter();
        Result success = Result.success("");
        out.write(JSONUtil.toJsonStr(success));
        out.flush();
        out.close();
    }
}
